<template>
	<view class="wrap">
		<!-- <js-lang title="home.title" :showBtn="true"></js-lang> -->
		<!-- 资产情况 + 审核快捷入口，仅在拥有商品管理菜单权限时显示 -->
		<view v-if="hasProductManagement">
			<view class="assets-card">
				<view class="assets-card-bg"></view>
				<view class="assets-card-content">
					<view class="assets-header">
					<view>
						<text class="assets-title">资产情况</text>
						<u-icon name="question-circle" size="32" color="#ffffff" @click="showAssetsHelp"></u-icon>
					</view>
					<u-icon name="setting" size="42" color="#ffffff" @click="navTo('/pages/inventoryManagement/setting')"></u-icon>
				</view>
				<view class="assets-total">
					<text class="total-label">总资产</text>
					<text class="total-value">¥ {{ formatMoney(assetsData.totalAssets) }}</text>
				</view>
				<view class="assets-content">
					<!-- 左侧环形图 -->
					<view class="chart-wrapper">
						<canvas 
							canvas-id="assetsChart" 
							class="assets-chart"
						></canvas>
					</view>
					<!-- 右侧详情列表 -->
					<view class="assets-detail">
						<view class="detail-item" v-for="(item, index) in assetsList" :key="index">
							<view class="detail-label-wrapper">
								<view class="color-dot" :style="{ backgroundColor: item.color }"></view>
								<text class="detail-label">{{ item.label }}</text>
							</view>
							<text class="detail-value" :class="{ 'negative': item.negative }">¥ {{ formatMoney(item.value) }}</text>
						</view>
					</view>
				</view>
				</view>
			</view>
			<!-- <u-swiper :height="300" :list="imgList" :title="false" @click="imgListClick"></u-swiper> -->
			<view class="toolbar">
				<u-grid class="toolbar-grid" :col="3" :border="false">
					<u-grid-item 
						v-for="(item, index) in menuList" 
						:key="index"
						:index="index" 
						@click="navTo(item.url)"
						class="toolbar-item"
					>
						<view class="toolbar-item-content">
							<view class="icon-wrapper">
								<u-badge v-if="item.count > 0" :count="item.count"></u-badge>
								<view class="icon-bg" :style="{ backgroundColor: item.color + '20' }">
									<u-icon class="grid-icon" :name="item.icon" :size="60" :style="{ color: item.color }"></u-icon>
								</view>
							</view>
							<view class="grid-text">{{ item.title }}</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</view>
		<!-- 使用动态菜单组件，只显示报表菜单 -->
		<dynamic-menu :menu-type="4"></dynamic-menu>

	</view>
</template>

<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
 import DynamicMenu from '@/components/dynamic-menu/dynamic-menu.vue';
export default {
	components: {
		DynamicMenu
	},
	data() {
		return {
			imgList: [
				{image: '/static/jeesite/banner/1.svg'},
				{image: '/static/jeesite/banner/2.svg'},
				{image: '/static/jeesite/banner/3.svg'}
			],

			todoCount: 0,

			menuList: [
				{
					title: '待发货',
					icon: 'clock',
					color: '#ea9a44',
					url: '/pages/inventoryManagement/classOrderList?orderStatus=1&title=待发货',
					count: 0
				},
				{
					title: '充值审核',
					icon: 'checkmark-circle',
					color: '#47cb66',
					url: '/pages/inventoryManagement/recharge/rechargeRecord?type=1&title=充值审核',
					count: 0
				},
				{
					title: '交款审核',
					icon: 'order',
					color: '#5a98ea',
					url: '/pages/inventoryManagement/stockOrderList?type=2&title=交款审核',
					count: 0
				}
			],
			
			// 资产数据
			assetsData: {
				accountBalance: 0,
				inventoryTotal: 0,
				pendingInboundTotal: 0,
				receivableAmount: 0,
				pendingCommission: 0,
				totalAssets: 0
			},
			chartWidth: 300, // rpx单位
			chartContext: null,

			// 是否拥有商品管理菜单（进销存权限）
			hasProductManagement: false

		};
	},

	onLoad() {
		this.checkProductManagementMenu();
		this.loadAssetsData();
		this.$nextTick(() => {
			this.initChart();
		});
	},

	onShow() {
		this.refreshCount();
		this.loadAssetsData();
	},
	methods: {
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		// 检查是否拥有商品管理菜单（通过路由菜单权限）
		async checkProductManagementMenu() {
			try {
				const res = await this.$u.api.menuRoute();
				const targetUrl = '/pages/inventoryManagement/productManagement';

				const hasUrl = (node) => {
					if (!node) return false;
					if (Array.isArray(node)) {
						return node.some(child => hasUrl(child));
					}
					if (node.url === targetUrl) {
						return true;
					}
					if (Array.isArray(node.children)) {
						return node.children.some(child => hasUrl(child));
					}
					return false;
				};

				this.hasProductManagement = hasUrl(res);
			} catch (e) {
				console.error('检查商品管理菜单权限失败:', e);
				this.hasProductManagement = false;
			}
		},
		refreshCount() {
			// 获取待办个数
			this.$u.api.orderManagement.listByShop().then(res => {
				if (res && res.data) {
					// 待发货：orderStatus = 1
					const pendingCount = res.data.filter(o => o.orderStatus == 1).length;
					
					// 更新 menuList 中对应的 count
					this.$set(this.menuList[0], 'count', pendingCount);
				}
			}).catch(err => {
				console.error('获取待办数量失败:', err);
			});
			
			// 获取充值审核数量
			this.$u.api.wallet.rechargeList({
				status: '0', // 待审核状态
				type: '1' // 查询所有记录
			}).then(res => {
				if (res && (res.result === 'true' || res.code === '1')) {
					const dataList = res.data || res.list || [];
					// 统计待审核数量（status === '0'）
					const rechargeAuditCount = dataList.filter(item => String(item.status || '0') === '0').length;
					// 更新充值审核的 count
					this.$set(this.menuList[1], 'count', rechargeAuditCount);
				}
			}).catch(err => {
				console.error('获取充值审核数量失败:', err);
			});
			
			// 获取交款审核数量（进货订单，orderStatus == 5 && payStatus == 2）
			this.$u.api.orderManagement.list({
				orderType: 2, // 进货订单
				byShop: 0
			}).then(res => {
				if (res && res.data) {
					// 交款审核：orderStatus == 5 && payStatus == 2
					const paymentAuditCount = res.data.filter(o => o.orderStatus == 5 && o.payStatus == 2).length;
					// 更新交款审核的 count
					this.$set(this.menuList[2], 'count', paymentAuditCount);
				}
			}).catch(err => {
				console.error('获取交款审核数量失败:', err);
			});
		},
		imgListClick(index) {
			console.log(`点击了第${index + 1}页图片`)
		},
		// 加载资产数据
		loadAssetsData() {
			this.$u.api.wallet.assetsSummary().then(res => {
				console.log('资产数据接口返回:', res);
				// 兼容 result 为 '1' 或 'true' 的情况
				if (res && (res.result == '1' || res.result == 'true' || res.result === true) && res.data) {
					this.assetsData = {
						accountBalance: parseFloat(res.data.accountBalance || 0),
						inventoryTotal: parseFloat(res.data.inventoryTotal || 0),
						pendingInboundTotal: parseFloat(res.data.pendingInboundTotal || 0),
						receivableAmount: parseFloat(res.data.receivableAmount || 0),
						pendingCommission: parseFloat(res.data.pendingCommission || 0),
						totalAssets: parseFloat(res.data.totalAssets || 0)
					};
					console.log('解析后的资产数据:', this.assetsData);
					this.$nextTick(() => {
						this.drawChart();
					});
				} else {
					console.warn('资产数据格式不正确:', res);
				}
			}).catch(err => {
				console.error('获取资产数据失败:', err);
				uni.showToast({
					title: '获取资产数据失败',
					icon: 'none'
				});
			});
		},
		// 初始化图表
		initChart() {
			this.chartContext = uni.createCanvasContext('assetsChart', this);
		},
		// 绘制环形图
		drawChart() {
			if (!this.chartContext) {
				this.initChart();
			}
			
			const ctx = this.chartContext;
			// 获取需要显示的数据（只显示正值的资产）
			const chartData = this.chartDataList;
			if (chartData.length === 0) {
				return;
			}
			
			// 计算总角度
			const total = chartData.reduce((sum, item) => sum + item.value, 0);
			if (total === 0) {
				return;
			}
			
			// 将rpx转换为px
			uni.getSystemInfo({
				success: (res) => {
					// 计算图表尺寸（rpx转px）
					const chartSize = (this.chartWidth / 900) * res.windowWidth;
					const centerX = chartSize / 2;
					const centerY = chartSize / 2;
					const radius = chartSize / 2 - (40 / 900) * res.windowWidth;
					const innerRadius = radius - (60 / 900) * res.windowWidth;
					
					// 清空画布
					ctx.clearRect(0, 0, chartSize, chartSize);
					
					let currentAngle = -Math.PI / 2; // 从顶部开始
					
					chartData.forEach((item, index) => {
						const angle = (item.value / total) * 2 * Math.PI;
						
						// 绘制外弧
						ctx.beginPath();
						ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + angle, false);
						ctx.arc(centerX, centerY, innerRadius, currentAngle + angle, currentAngle, true);
						ctx.closePath();
						ctx.setFillStyle(item.color);
						ctx.fill();
						
						currentAngle += angle;
					});
					
					ctx.draw();
				}
			});
		},
		// 格式化金额
		formatMoney(value) {
			if (!value && value !== 0) return '0.00';
			return parseFloat(value).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		},
		// 显示帮助信息
		showAssetsHelp() {
			uni.showModal({
				title: '资产说明',
				content: '总资产 = 账户余额 + 库存总额 + 应收欠款 + 待入库商品 + 待收佣金',
				showCancel: false
			});
		}
	},
	computed: {
		// 图表数据列表（只显示主要资产，排除待入库和待收佣金）
		chartDataList() {
			const list = [];
			if (this.assetsData.inventoryTotal > 0) {
				list.push({
					label: '库存总额',
					value: this.assetsData.inventoryTotal,
					color: '#91CB74' // 绿色
				});
			}
			if (this.assetsData.accountBalance > 0) {
				list.push({
					label: '账户余额',
					value: this.assetsData.accountBalance,
					color: '#5a98ea' // 蓝色
				});
			}
			if (this.assetsData.receivableAmount > 0) {
				list.push({
					label: '应收欠款',
					value: this.assetsData.receivableAmount,
					color: '#ea9a44' // 橙色
				});
			}
			if (this.assetsData.pendingInboundTotal > 0) {
				list.push({
					label: '待入库商品',
					value: this.assetsData.pendingInboundTotal,
					color: '#3B4436',
					negative: false
				});
			}
			if (this.assetsData.pendingCommission > 0) {
				list.push({
					label: '待收佣金',
					value: this.assetsData.pendingCommission,
					color: '#f56c6c',
					negative: false
				});
			}
			return list;
		},
		// 资产详情列表
		assetsList() {
			return [
				{
					label: '账户余额',
					value: this.assetsData.accountBalance,
					color: '#5a98ea',
					negative: false
				},
				{
					label: '库存总额',
					value: this.assetsData.inventoryTotal,
					color: '#91CB74',
					negative: false
				},
				{
					label: '应收欠款',
					value: this.assetsData.receivableAmount,
					color: '#ea9a44',
					negative: false
				},
				{
					label: '待入库商品',
					value: this.assetsData.pendingInboundTotal,
					color: '#3B4436',
					negative: false
				},
				{
					label: '待收佣金',
					value: this.assetsData.pendingCommission,
					color: '#f56c6c',
					negative: false
				}
			];
		}
	}
};
</script>

<style lang="scss">
@import 'index.scss';
page {
	background-color: #f8f8f8;
}

::v-deep .u-badge {
	position: absolute;
	top: 0rpx !important;
	right: -30rpx !important;
}

.card {
	background-color: #fff;
	border-radius: 20rpx;
	margin: 20rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.title {
	font-size: 24rpx;
	color: #666;
	// font-weight: bold;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
}

.grid-item-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100%;
	padding: 10rpx 0;
}

.toolbar {
	background-color: #fff;
	border-radius: 20rpx;
	margin: 20rpx;
	padding: 0rpx 20rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08),
				0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.toolbar-grid {
	width: 100%;
}

.toolbar-item {
	padding: 10rpx;
}

.toolbar-item-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100%;
	padding: 20rpx 10rpx;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.95);
	}
}

.icon-wrapper {
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 16rpx;
}

.icon-bg {
	width: 120rpx;
	height: 120rpx;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.toolbar-item-content:active .icon-bg {
	transform: scale(0.9);
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.15);
}

.grid-icon {
	position: relative;
	z-index: 1;
	margin-bottom: 0;
}

.grid-text {
	font-size: 28rpx !important;
	color: #333;
	text-align: center;
	font-weight: 500;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

/* 资产情况卡片 */
.assets-card {
	position: relative;
	border-radius: 20rpx;
	margin: 20rpx;
	overflow: hidden;
	box-shadow: 
		0 4rpx 16rpx rgba(102, 126, 234, 0.3),
		0 8rpx 32rpx rgba(102, 126, 234, 0.2),
		0 16rpx 48rpx rgba(0, 0, 0, 0.15),
		inset 0 1rpx 0 rgba(255, 255, 255, 0.3);
	border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.assets-card-bg {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-image: 
		radial-gradient(circle at 20% 30%, rgba(255, 255, 255, 0.2) 0%, transparent 50%),
		radial-gradient(circle at 80% 70%, rgba(255, 255, 255, 0.15) 0%, transparent 50%),
		radial-gradient(circle at 40% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
		linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
	background-size: 200% 200%, 150% 150%, 180% 180%, 100% 100%;
	background-position: 0% 0%, 100% 100%, 50% 50%, 0% 0%;
	z-index: 1;
}

.assets-card-bg::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	border-radius: 20rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
	box-shadow: 
		inset 0 2rpx 8rpx rgba(255, 255, 255, 0.4),
		inset 0 -2rpx 8rpx rgba(0, 0, 0, 0.2);
	pointer-events: none;
	z-index: 1;
}

.assets-card-content {
	position: relative;
	z-index: 2;
	padding: 30rpx;
}

.assets-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.assets-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
}

.assets-total {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 40rpx;
	padding-bottom: 30rpx;
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
}

.total-label {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-bottom: 10rpx;
}

.total-value {
	font-size: 50rpx;
	font-weight: bold;
	color: #ffffff;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.assets-content {
	display: flex;
	align-items: center;
}

.chart-wrapper {
	flex-shrink: 0;
	width: 250rpx;
	height: 250rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.assets-chart {
	width: 250rpx;
	height: 250rpx;
}

.assets-detail {
	position: relative;
	flex: 1;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 16rpx;
	padding: 24rpx;
	box-shadow: 
		0 4rpx 12rpx rgba(0, 0, 0, 0.08),
		0 8rpx 24rpx rgba(0, 0, 0, 0.06),
		inset 0 1rpx 0 rgba(255, 255, 255, 0.8),
		inset 0 -1rpx 0 rgba(0, 0, 0, 0.05);
	border: 1rpx solid rgba(255, 255, 255, 0.6);
}

.assets-detail::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	border-radius: 16rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.8);
	box-shadow: 
		inset 0 2rpx 6rpx rgba(255, 255, 255, 0.9),
		inset 0 -2rpx 6rpx rgba(0, 0, 0, 0.08);
	pointer-events: none;
	z-index: 1;
}

.detail-item {
	position: relative;
	z-index: 2;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.detail-item:last-child {
	margin-bottom: 0;
}

.detail-label-wrapper {
	display: flex;
	align-items: center;
	flex: 1;
}

.color-dot {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	margin-right: 15rpx;
}

.detail-label {
	font-size: 28rpx;
	color: #666;
}

.detail-value {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.detail-value.negative {
	color: #f56c6c;
}
</style>

